/*
 * @Author: Snitro
 * @Date: 2021-02-23 09:48:52
 * @LastEditors: Snitro
 * @LastEditTime: 2021-02-23 14:49:52
 * @Description: tm1637 驱动
 */

#include "tm1637.h"

/**
 * @description: 设置TM1637模式
 * @param {uint8_t} set TM1637_Settings_Read    读取按键模式
 *                      TM1637_Settings_Write   点亮LED模式
 * @return {HAL_OK}     设置成功
 * @return {HAL_ERROR}  设置失败
 */
HAL_StatusTypeDef TM1637_Mod(uint8_t set) {
    Software_I2C_Start();
    Software_I2C_WriteByte(TM1637_Settings | TM1637_Settings_Address_ADD | set);
    HAL_StatusTypeDef ret = Software_I2C_WaitACK();
    Software_I2C_Stop();
    return ret;
}

/**
 * @description: 设置数码管亮度
 * @param {uint8_t} light 亮度值，取0-8，0为关闭数码管，8为最亮
 * @return {HAL_OK}     设置成功
 * @return {HAL_ERROR}  设置失败
 */
HAL_StatusTypeDef TM1637_Light(uint8_t light) {
    if (light) light |= 0x08;
    light |= 0x80;

    Software_I2C_Start();
    Software_I2C_WriteByte(light);
    HAL_StatusTypeDef ret = Software_I2C_WaitACK();
    Software_I2C_Stop();
    return ret;
}

/**
 * @description: 点亮数码管
 * @param {uint8_t} GRID    使用 TM1637_GRID_x ,其中x填入 1-6 以内的数字
 *                          点亮多个数码管时用 | 连接
 * @param {uint8_t} *cod    每位数码管的段编码，第x位二进制位1代表点亮第x段
 * @return {HAL_OK}     点亮成功
 * @return {HAL_ERROR}  点亮失败
 */
HAL_StatusTypeDef TM1637_Display(uint8_t GRID, uint8_t *cod) {
    HAL_StatusTypeDef ret = HAL_OK;
    uint8_t g, add_flag = 0, cod_pos = 0;
    for (g = 0; g < 6; g++) {
        if (!(GRID & (1 << g))) {
            add_flag = 0;
            continue;
        }

        //设置首地址
        if (!add_flag) {
            Software_I2C_Start();
            Software_I2C_WriteByte(0xc0 | g);
            ret |= Software_I2C_WaitACK();
        }

        //输出段编码
        Software_I2C_WriteByte(cod[cod_pos++]);
        ret |= Software_I2C_WaitACK();

        if (g == 5 || !(GRID & (1 << (g + 1)))) {
            add_flag = 0;
            Software_I2C_Stop();
        } else if (GRID & (1 << (g + 1)))
            add_flag = 1;
    }

    return ret;
}